package org.jactao.common;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by fanzetao on 2018/4/4.
 */
public class LResponseFuture {

    private CountDownLatch latch = new CountDownLatch(1);

    public LResponseFuture(LResponse response) {
        this.response = response;
    }

    public LResponseFuture() {
    }

    private LResponse response;

    public CountDownLatch getLatch() {
        return latch;
    }

    public void setLatch(CountDownLatch latch) {
        this.latch = latch;
    }

    public LResponse getResponse() {
        return response;
    }

    public void setResponse(LResponse response) {
        this.response = response;
        latch.countDown();
    }

    public LResponse get() {
        if(response == null) {
            try {
                latch.await();
                return response;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public LResponse get(long timeout) throws InterruptedException{
        if(response == null) {
            try {
                if(latch.await(timeout, TimeUnit.MILLISECONDS))
                    return response;
                else
                    throw new LException("timeout " + timeout + "ms");
            } catch (InterruptedException e) {
                throw e;
            }
        }
        return response;
    }
}
